﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SocketInfo
{
    public string saveIp;

    public SocketInfo()
    {

    }

    public SocketInfo(string ip)
    {
        saveIp = ip;
    }
}

public class SocketClientModule : MonoBehaviour {
    public SocketClient _Client { get;private set;}
    public NetMsgCenter _msgCenter { get; private set; }

    private string _curConnectIp;//记录当前连接的ip，用于自动重连
    private string _curConnectEndPoint;

    public bool _autoConect;

    void Start ()
    {
        
    }

    public void Init()
    {
        _Client = new SocketClient();
        Debug.Log("初始化启动客户端完毕");
        _msgCenter = new GameObject("msgCenter", typeof(NetMsgCenter)).GetComponent<NetMsgCenter>();
        _msgCenter.transform.SetParent(this.transform);
        _Client.ReceiveCallBack += (x) => { _msgCenter._netRcvMsg.Enqueue(x); };
    }

    public void Connect(string set_ip, string endPoint_set)
    {
        _Client.Connect(set_ip, endPoint_set);//连接服务器
        _curConnectIp = set_ip;
        _curConnectEndPoint = endPoint_set;
        if (_autoConect)
        {
            StartCoroutine(AutoReconect());
        }
    }

    private void OnDestroy()
    {
        _Client.CloseConnect();
    }

    public void NetSend(string msgType,string msg)
    {
        _Client.Send(msgType,msg);
    }

    IEnumerator AutoReconect()
    {
        wait: yield return new WaitForSeconds(5);
        //while (true)
        {
            if (!_Client.IsConnected())
            {
                _Client.CloseConnect();
                _Client.Connect(_curConnectIp, _curConnectEndPoint);
            }
        }
        goto wait;
    }
}
